const axios = require('axios')
//获取token操作数据库权限
const qs = require('qs')
const result = require('./handle')

//拼接参数
let parms = qs.stringify({
    grant_type :'client_credential', 
    appid : 'wx3739e0ac0a461528',
    secret : '874c9154161ccee2ecb06ce283665b2e'
})
//获取tokenurl
let url = 'https://api.weixin.qq.com/cgi-bin/token?'+parms
//数据库增加url
let addUrl = 'https://api.weixin.qq.com/tcb/databaseadd?access_token='
//数据库查询url
let whereUrl = 'https://api.weixin.qq.com/tcb/databasequery?access_token='
//数据库更新url
let updateUrl = 'https://api.weixin.qq.com/tcb/databaseupdate?access_token='
//订阅消息
let subscribeMsg = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='
//小程序桌号码
let QRcode = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='
let env = 'cloud1-8gkhb3hhe0b44a8f'
class getToken{
    constructor(){

    }
    //获取token
    async gettoken(){
        try {
            let token = await axios.get(url)
            if (token.status == 200) {
                return token.data.access_token
            }else{
                throw 'tokenfail'
            }
        } catch (error) {
            throw  new result(error,500)
        }
    }
    //调用云开发接口
    async posteve(dataurl,query){
        try {
            let token = await this.gettoken()
            let data = await axios.post(dataurl+token,{env,query})
            if (data.data.errcode == 0) {
                return data.data
            }else{
                throw '请求出错'
            }
        } catch (error) {
            throw new result(error,500)
        }

    }
    async subscribe(touser,data){
        try {
            let token  = await this.gettoken()
            let OBJ = {touser,data,template_id:'dszz74hyWqce2CCFeMFrpUQnB4Mie2UveNvKluDrCAk',page:'pages/my-order/my-order',miniprogram_state:'developer'}
            let calldata = await axios.post(subscribeMsg+token,OBJ)
            return 'success'
        } catch (error) {
            throw new result(error,500)
        }
    }
    //生成小程序码
    async qrcode(number){
        let token  = await this.gettoken()
        let OBJ = JSON.stringify({path:'pages/index/index?number='+number})
        try {
            let calldata = await axios.post(QRcode+token,OBJ,{responseType:'arraybuffer'})
            return calldata
        } catch (error) {
            throw new result(error,500)
        }
    }
}
module.exports = {getToken,addUrl,whereUrl,updateUrl}